<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../easyui/themes/icon.css">
<script type="text/JavaScript" src="../api/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="../easyui/jquery.easyui.min.js"></script>
<script type='text/JavaScript' src='../../zbw_reporting/scripts/framework_include.js'></script>
<title>Drilldown Component</title>
<style type="text/css">

    body {
        width: 100%;
        height: 100%;
        position: absolute;
        padding: 0px;
        margin: 0px;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        min-width: 700px;
    }
    .mainLayout {
        float: left;
        width: 98%;
        height: 95%;
        margin-top: 10px;
        margin-left: 10px;
    }
    div.arrows {
        padding-left: 24px;
        padding-right: 24px;
        vertical-align: middle;
        width: 24px;
        display: inline-block;
        padding-top: 10%;
    }
    button.inputToggler {
        background-image: url("../easyui/themes/icons/edit 16x16.png");
        height: 16px;
        width: 16px;
        vertical-align: middle;
        border: 0;
    }
    a.buttonStyle {
        background-color: #e0e0e0;
        border: 1px;
        border-color: silver;
        border-style: solid;
    }
</style>

<script type="text/javascript">
// [REQUIRED] SCRIPT FOR INTEGRATION WITH BOI
var BOI = parent.BOI; //REQUIRED
var BOIData = parent.BOIData; //REQUIRED
var properties = { //REQUIRED
    querymeta:undefined,
    data:undefined,
    drilldowns:undefined,
    headerColumns:undefined
};

var initialize = function initialize() {//REQUIRED //initialization function ... see below..
    /*---- begin your component custom initialization code ----*/
    //set property values to dom elements if needed
    refreshProperties();
};
var refreshGrids = function refreshGrids() {
    $('#drilldownTable').datagrid(
    {
        fitColumns:true,
        singleSelect:true,
        css:{
            width:'100%',
            height:'auto'
        },
        columns:[
            [
                {title:'Source Column', field:'SOURCE_COLUMN', width:300},
                {title:'Target Report', field:'TARGET_BO', width:300},
                {title:'Target Report Techname', field:'TARGET_QUERY', width:300}
            ]
        ],
        onClickRow:function (rowIndex, rowData) {
            mapDrilldownInfo(rowData);
        }
    });
    $('#parametersTable').datagrid(
    {
        fitColumns:true,
        singleSelect:true,
        css:{
            width:'100%',
            height:'auto'
        },
        columns:[
            [
                {title:'Variable Name', field:'NAME', width:250},
                {title:'Variable Techname', field:'TECHNAME', width:250},
                {title:'Info Obejct Name', field:'IOBJNM', width:200},
                {title:'Value to Pass', field:'VALUE', width:300, formatter:addSourceDropdown},
                {title:'Map Axis', field:'AXIS', width:300, formatter:addAxisDropDown}
            ]
        ]
    });
};

var refresh = function refresh() { //REQUIRED function to be called by parent at anytime to refresh data.
    var report_id = parent.report_id;
    refreshGrids();
    if (parent.kpi.DRILL_DOWNS != null && parent.kpi.DRILL_DOWNS.length > 0) {
        properties.drilldowns = clone(parent.kpi.DRILL_DOWNS);
        $('#drilldownTable').datagrid('loadData', properties.drilldowns);
    }
    $('#drilldownColumn').html(parent.headerColumnsOptions);
    populateTargetReport();
    populateSource();
};
var refreshProperties = function refreshProperties() { //REQUIRED function to be called by parent when a property change occurs
};
var save = function save() {
    parent.kpi.drilldowns = clone(properties.drilldowns);
}
var variables = [];
var manualInput = [];
var targetReportsList = [];
$(document).ready(function () {
    if (BOI.app_id == null)
        BOI.app_id = BOIData.app_id;
});
function mapDrilldownInfo(drilldownInfo) {
    if (drilldownInfo == null)
        drilldownInfo = new DrillDown();
    if (drilldownInfo.TARGET_BO != '')
        $('#targetReportSelect').val(drilldownInfo.TARGET_BO);
    if (drilldownInfo.SOURCE_COLUMN != '')
        $('#drilldownColumn').val(drilldownInfo.SOURCE_COLUMN);
    if (drilldownInfo.TARGET_QUERY != '') {
        $('#targetQueryInput').val(drilldownInfo.TARGET_QUERY);
        mapVariables(drilldownInfo, clone(drilldownInfo.MAPPINGS));
    }
}
function mapVariables(drilldownInfo, clonedVariables) {
    if (drilldownInfo.MAPPINGS.length != 0) {
        //check selected series against the series from the query...
        var selectedVariable = new Mapping();
        var matchedVariable = new Mapping();
        for (var i = 0; i < drilldownInfo.MAPPINGS.length; i++) {
            selectedVariable = drilldownInfo.MAPPINGS[i];
            for (var j = 0; j < clonedVariables.length; j++) {
                matchedVariable = clonedVariables[j];
                if (selectedVariable.TECHNAME == matchedVariable.TECHNAME) {
                    if (selectedVariable.MAPPED_VALUE != '' || selectedVariable.VALUE == '') {
                        matchedVariable.VALUE = selectedVariable.MAPPED_VALUE;
                        manualInput[j] = false;
                    }
                    else {
                        matchedVariable.VALUE = selectedVariable.VALUE;
                        manualInput[j] = true;
                    }
                    matchedVariable.AXIS = selectedVariable.AXIS;
                    break;
                }
            }
        }
    }

    $('#parametersTable').datagrid('loadData', clonedVariables);
    for (var i = 0; i < $('#parametersTable').datagrid('getData').rows.length; i++) {
        $('#parametersTable').datagrid('refreshRow', i);
    }
}
function getTargetVariableInfo() {
    parseVariablesInfo(properties.querymeta);
    resetDataGrid();
}
function resetDataGrid() {
    $('#parametersTable').datagrid('loadData', clone(variables));
    for (var i = 0; i < $('#parametersTable').datagrid('getData').rows.length; i++) {
        $('#parametersTable').datagrid('refreshRow', i);
    }
}
function parseVariablesInfo(currentVariable, index) {
    var targetVariable = new Mapping();
    targetVariable.NAME = currentVariable.description;
    targetVariable.TECHNAME = currentVariable.name;
    targetVariable.IOBJNM = currentVariable.IOBJNM;

    variables.push(targetVariable);
    manualInput[index] = false;
}
function populateSource() {
    for (var source in properties.headerColumns) {
        $("#drilldownColumn").append($("<option value='" + source + "'>" + source + "</option>"));
    }
}
function populateTargetReport() {
    var arr = [];
    BOIData.list.getCatalog(BOIData.app_id, 'xml'
            // "ADMIN" or "USER"
            , "ADMIN"
            , function (data) {
                reportCatalog(data);
            }, arr);
}
function reportCatalog(data) {
    targetReportsList = $(data).find("node:not([type*='FOLDER'])");
    targetReportsList.prepend({'id':'', 'title':'', 'tech_name':'', 'type':''});
    targetReportsList.each(function () {
      this.tech_name = $(this.outerHTML).attr('tech_Name');
      this.type = $(this.outerHTML).attr('type');
      this.variables = new Object();
      $("#targetReportSelect").append($("<option value='" + this.tech_name + "'>" + this.title + "</option>"));
    });
}
function refreshQueryTechname(event) {
    var selectedIndex = event.currentTarget.selectedIndex;
    var targetReport = undefined;
    if (targetReportsList[selectedIndex].tech_name == $("#targetReportSelect").val()) {
        targetReport = clone(targetReportsList[selectedIndex]);
    }
    else {
        for (var i = 0; i < targetReportsList.length; i++) {
            if (targetReportsList[i].tech_name == $("#targetReportSelect").val()) {
                targetReport = clone(targetReportsList[i]);
                break;
            }
        }
    }
    $("#targetQueryInput").val($("#targetReportSelect").val());
    BOI.loadReportMeta(targetReport, function (data) {
        variables = new Array();
        var i = 0;
        for (var reportVariable in targetReport.variables) {
            parseVariablesInfo(targetReport.variables[reportVariable], i);
            i++;
        }

        $('#parametersTable').datagrid('loadData', clone(variables));
        for (var i = 0; i < $('#parametersTable').datagrid('getData').rows.length; i++) {
            $('#parametersTable').datagrid('refreshRow', i);
        }
    }, 'Y');
}
function addDrilldown() {
    if (properties.drilldowns == null)
        properties.drilldowns = new Array();

    if ($("#drilldownTable").datagrid("getSelected") != null)
        var selectedRow = $("#drilldownTable").datagrid("getSelected");

    if (selectedRow == null) {
        selectedRow = new DrillDown();
        properties.drilldowns.push(selectedRow);
        mapDrilldownInfo(selectedRow);
    }
    selectedRow.SOURCE_COLUMN = $('#drilldownColumn').val();
    selectedRow.TARGET_BO = $('#targetReportSelect').val();
    selectedRow.TARGET_QUERY = $('#targetQueryInput').val();
    selectedRow.MAPPINGS = clone($("#parametersTable").datagrid("getData").rows);
    $('#drilldownTable').datagrid('loadData', properties.drilldowns);
    resetFields();
}

function resetFields() {
    $("#targetReportSelect").val("");
    $("#targetQueryInput").val("");
    $("#drilldownColumn").val("");
    for (var i = 0; i < manualInput.length; i++) {
        manualInput[i] = false;
    }
    resetDataGrid();
}

function addSourceDropdown(value, row, index) {
    var inputToggler = $('<button class="inputToggler" index="' + index + '" onclick="toggelInput(event)"> </button> ')
    if (!manualInput[index]) {
        var sourceDropdown = $('<select onchange="changeSelectedInfoObject(event)" style="width: 90%;"></select>');
        sourceDropdown.append($('<option></option>'));
        var optionsHTML = parent.headerColumnsOptions;
        $(optionsHTML).each(function(){
            var selectOption = $('<option value="' + this.value + '">' + this.text + '</option>');
            if (row.VALUE == this.value)
                selectOption.attr('selected', true);
            sourceDropdown.append(selectOption);
        });
        return sourceDropdown.get(0).outerHTML + inputToggler.get(0).outerHTML;
    }
    else {
        var textInput = $('<input type="text" onkeyup="changeSelectedInfoObject(event)" style="width: 90%;" value="' + row.VALUE + '">');
        return textInput.get(0).outerHTML + inputToggler.get(0).outerHTML;
    }
}
function addAxisDropDown(value, row, index) {
    var sourceDropdown = $('<select onchange="changeSelectedAxis(event)" style="width: 90%;"></select>');
    var seriesOption = $('<option value="series" > Series </option>');
    var xOPtion = $('<option value="x"> X </option>');
    if (row.AXIS == 'series')
        seriesOption.attr('selected', true);
    else if (row.AXIS == 'x')
        xOPtion.attr('selected', true);

    sourceDropdown.append($('<option value="" ></option>'));
    sourceDropdown.append(seriesOption);
    sourceDropdown.append(xOPtion);
    return sourceDropdown.get(0).outerHTML;
}
function changeSelectedInfoObject(event) {
    var selectedValue = event.currentTarget.value;
    var selectedRow = $('#parametersTable').datagrid('getSelected');

    if ($(event.currentTarget).get(0).tagName.toLowerCase() != 'select') {
        selectedRow.VALUE = selectedValue;
        selectedRow.MAPPED_VALUE = '';
    }
    else {
        selectedRow.MAPPED_VALUE = selectedValue;
        selectedRow.VALUE = '';
    }
}
function changeSelectedAxis(event) {
    var selectedValue = event.currentTarget.value;
    var selectedRow = $('#parametersTable').datagrid('getSelected');
    selectedRow.AXIS = selectedValue;
}
function toggelInput(event) {
    var rowIndex = $(event.currentTarget).attr('index');
    manualInput[rowIndex] = !manualInput[rowIndex];
    $('#parametersTable').datagrid('refreshRow', rowIndex);
}
function editDrilldown() {
    if ($(drilldownTable).datagrid('getSelected') != null) {
        addDrilldown($(drilldownTable).datagrid('getSelected'));
    }
    else {
        alert('please select a drill down to edit');
    }
}
function deleteDrilldown() {
    if ($("#drilldownTable").datagrid("getSelected") == null) {
        alert("please select a drilldown to be deleted!");
    }
    else {
        var confirmationDialog;
        if ($("#dialog").get(0) == null) {
            confirmationDialog = $("<div id='dialog'>" +
                    "<p>The selected item will be permanently deleted and cannot be recovered. Are you sure?</p>" +
                    "</div>");
            confirmationDialog.appendTo('body');
        }
        else
            confirmationDialog = $("#dialog");


        confirmationDialog.dialog({
            title:"Confirm Remove Drilldown",
            closed:false,
            cache:false,
            modal:true,
            style:{
                width:"400px",
                height:"200px",
                padding:"10px"
            },
            buttons:[
                {
                    text:"OK",
                    iconCls:"icon-ok",
                    handler:function () {
                        var cuurentDrilldownIndex = $("#drilldownTable").datagrid("getRowIndex", $("#drilldownTable").datagrid("getSelected"));
                        $("#drilldownTable").datagrid("deleteRow", cuurentDrilldownIndex);
                        resetFields();
                        confirmationDialog.dialog("close");
                    }
                },
                {
                    text:"Cancel",
                    iconCls:"icon-cancel",
                    handler:function () {
                        confirmationDialog.dialog("close");
                    }
                }
            ]
        });
    }
}
</script>

<script type="text/javascript">
    function DrillDown() {
        this.SOURCE_COLUMN = '';
        this.TARGET_BO = '';
        this.TARGET_QUERY = '';
        this.MAPPINGS = [];
    }
    function Mapping() {
        this.TECHNAME = '';
        this.NAME = '';
        this.IOBJNM = '';
        this.MAPPED_VALUE = '';
        this.VALUE = '';
        this.AXIS = '';
    }
    function clone(obj) {
        // Handle the 3 simple types, and null or undefined
        if (null == obj || "Object" != typeof obj) return obj;

        // Handle Date
        if (obj instanceof Date) {
            var copy = new Date();
            copy.setTime(obj.getTime());
            return copy;
        }
        // Handle Array
        if (obj instanceof Array) {
            var copy = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                copy[i] = clone(obj[i]);
            }
            return copy;
        }
        // Handle Object
        if (obj instanceof Object) {
            var copy = {};
            for (var attr in obj) {
                if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
            }
            return copy;
        }
        throw new Error("Unable to copy obj! Its type isn't supported.");
    }
</script>

</head>
<body>

<div class="mainLayout">
    <form class="easyui-form">
        <fieldset>
            <legend> Drilldown Settings</legend>
            <div>
                <label></label>

                <a id="saveDrilldownSettingsbtn" class="easyui-linkbutton buttonStyle" data-options="plain:true"
                   href="javascript:void(0)" onclick="addDrilldown()">Save</a>

                <a href="javascript:void(0)" class="easyui-linkbutton buttonStyle" data-options="plain:true"
                   onclick="resetFields()">
                    Reset Fields
                </a>
                <a href="javascript:void(0)" class="easyui-linkbutton buttonStyle" data-options="plain:true"
                   onclick="deleteDrilldown()">
                    Delete Drilldown
                </a>

            </div>

            <table id="drilldownTable" style="float: left; margin-left: 5px;">
            </table>
            <br/>

            <div id="variablesMapping">
                <div style="padding:10px;">
                    <form class="easyui-form">
                        <fieldset>
                            <div>
                                <label>Target Report</label>
                                <select id="targetReportSelect" onchange="refreshQueryTechname(event)"> </select>
                            </div>

                            <div>
                                <label> Target Query Techname: </label>
                                <input id="targetQueryInput" type="text"
                                       placeholder="InfoProvider/Query e.g. ZEHSC_C09/ZEH_EPD_FINDINGS_BY_FUND">
                                <br/>
                                <br/>
                                <label>Source:</label>
                                <select id="drilldownColumn">
                                    <option value=""></option>
                                </select>
                                <br/>
                                <br/>
                                <label style="float: left;">Mapping: </label>
                                <table id="parametersTable" style="float: left; margin-left: 5px;">
                                </table>
                            </div>
                        </fieldset>
                    </form>
                </div>
            </div>

        </fieldset>
    </form>
</div>


</body>
</html>